import config from '@/common/config.js'
import { useUserStore } from '@/stores/user.js'

function service(options = {}) {
	options.url = config.baseUrl + options.url
	options.timeout = 30 * 1000
	options.responseType = 'json'
	options.header = {}
	const token = uni.getStorageSync('token')
	if (token) {
		options.header['Authorization'] = 'Bearer ' + token
	}
	return new Promise((resolve, reject) => {
		options.success = response => {
			if (response.statusCode === 200) {
				if (response.data.code === 200) {
					resolve(response.data)
				} else if (response.data.code === 401) {
					useUserStore().removeInfo()
					uni.reLaunch({
						url: '/pages/login/login'
					})
				} else {
					uni.showToast({ title: response.data.msg, icon: 'none' })
					reject()
				}
			} else {
				uni.showToast({ title: response.errMsg, icon: 'none' })
				reject()
			}
		}
		options.fail = error => {
			uni.showToast({ title: '连接服务异常', icon: 'none' })
			reject(error)
		}
		uni.request(options)
	})
}

export default service